libname bond 'D:\name your local directory';
libname factor 'D:\name your local directory\Ken French Data Library';


***************************************************************************************************************************************************
*For calculation of the bond market factor (MKTBond)
*Needs the following file as input: LTB3 from the DataMerge step, and risk free rate (RF) from Ken French data library
***************************************************************************************************************************************************;

%LET IN_DATA=LTB3;
%LET OUT =MKTBond;


proc sort data=bond.&IN_DATA (keep=date complete_cusip return AmountOut TMaturity)  out=temp1;
by date complete_cusip;
run;

proc means data=temp1 min p1 p5 p25 mean p75 p95 p99 max;
var return;
run;


data temp2; 
set temp1; 
AmountOut=AmountOut/1000; *in billions;
if TMaturity<=1 then delete;
if not missing(AmountOut);
run;


proc means data=temp2 noprint;
by date;
var return/weight=AmountOut;
output out=MKTBond mean(return)=MKTBond;
run;

data MKTBond1;
set MKTBond;
yyyymm=year(date)*100+month(date);
run;


*merge with RF from Ken French factor library;
proc sql;
create table MKTBond2 as select a.*, b.rf
from MKTBond1 as a left join factor.factors as b
on a.yyyymm=b.yyyymm;
quit;


data MKTBond3;
set MKTBond2;
MKTBond=MKTBond-rf;
yyyymm=year(date)*100+month(date);
if 200208<=yyyymm<=202112;
keep date MKTBond yyyymm rf;
run;

proc means data=MKTBond3 mean t;
var MKTBond;
where 200208<=yyyymm<=202112;
run;

data bond.&out;
set MKTBond3;
run;


